from flickrapi import FlickrAPI
from garetjax import config
from models import Photo, Owner
from django.conf import settings

def flickrapi(key=None, secret=None, token=None):
    if key is None:
        key = config.get('flickr:api_key')
    
    if secret is None:
        secret = config.get('flickr:api_secret')
    
    return FlickrAPI(key, secret, token=token)

def process_import(api, count):
    user_id = config.get('flickr:user_id')
    per_page = 500
    
    pages = int(count / float(per_page)) # Integer division!
    
    photo_count = 1
    for page in range(1, pages + 2):
        rsp = api.people_getPublicPhotos(user_id=user_id, per_page=per_page, page=page)

        for photo in rsp.find('photos').getiterator('photo'):
            o, created = Owner.objects.get_or_create(nsid=photo.attrib['owner'])
            query = {
                'flickr_id': photo.attrib['id'],
                'secret': photo.attrib['secret'],
                'owner': o,
                'server': photo.attrib['server'],
                'farm': photo.attrib['farm']
            }
            p, created = Photo.objects.get_or_create(**query)

            p.is_public = photo.attrib['ispublic']
            p.is_friend = photo.attrib['isfriend']
            p.is_family = photo.attrib['isfamily']
            p.title = photo.attrib['title']

            # @TODO: notes and tags

            # we get the additional informations for the photo only if the object
            # has beeen created
            p.save(get_details=created)
            
            if photo_count % 10:
                config.set('flickr:imported', photo_count)
            
            photo_count += 1
            
            
            
            